// import {defineAsyncComponent} from 'vue';
import {resolve, getRouteMeta, renameRouteComponent} from '@/components/layout/index.ts';
import {Menu, MenuDataPro, ResolveConfigs, RouteData, ResolveData} from '@/components/layout/index.ts';
import global from '@/utils/global';

const files = import.meta.glob('@/views/pages/**/**.vue');

export const resolveMenus = (menus: any): ResolveData<MenuDataPro, RouteData> => {
  return resolve(menus, {
    options: {
      rootPath: global.mainPage.path,
      homeIcon: global.homePage.icon,
      homeName: global.homePage.title,
      homePath: global.homePage.path,
    },
    getMenu: getMenuData,
    getRoute: getRouteData
  });
};

export const getMenuData = (menu: Menu, children: MenuDataPro[], path: string, configs: ResolveConfigs): MenuDataPro => {
  return {
    id: menu.id,
    name: menu.name,
    path: menu.fullPath,
    href: menu.href,
    iconName: menu.icon,
    index: menu.fullPath,
    parentId: menu.parentId,
    children: children.length > 0 ? children : undefined
  };
};

export const getRouteData = (menu: Menu, children: RouteData[], path: string, configs: ResolveConfigs): RouteData => {
  if (!menu.fullPath) {
    throw new Error(menu.name + ' 配置的菜单 path 为空');
  }
  const component = getComponent(menu, path);
  if (!component) {
    console.error(`未找到该 ${path} 路径所对应的组件：${menu.component || path}`);
    return {
      name: menu.id,
      path: menu.fullPath,
      meta: {},
      component: () => import('@/views/error/error/index.vue'),
      children: []
    };
  }
  return {
    name: menu.id,
    path: menu.fullPath,
    meta: getRouteMeta(menu),
    component: renameRouteComponent(menu.fullPath, component),
    children: children
  };
};

export const getComponent = (menu: Menu, path: string): any => {
  const component = menu.component;
  let componentPath = undefined;
  if (component) {
    if (menu.iframe) {
      return () => import('@/views/layout/frame/index.vue');
    } else {
      componentPath = component;
    }
  } else if (path) {
    componentPath = `view/pages/${path}`;
  }
  // return () => import.meta.glob([`@/${componentPath}.vue`]);
  // return (resolve) => require([componentPath], resolve);
  // return defineAsyncComponent(() => import(/* @vite-ignore */ componentPath));
  // return () => import('@/views/pages/system/menu/index.vue');
  // return () => import(`@/${componentPath}.vue`);
  // return defineAsyncComponent(() => import(`@/${componentPath}.vue`));
  return files[`/src/${componentPath}.vue`] || files[`/src/${componentPath}/index.vue`];
};

export const isUrl = (url: string | undefined): boolean => {
  if (url) {
    return /^url:.*/.test(url);
  }
  return false;
};

export const fetchRoute = (routes: RouteData[], nameFn: (route: RouteData) => void) => {
  if (routes && routes.length > 0) {
    for (let i = 0; i < routes.length; i++) {
      const route = routes[i];
      if (route && route.name) {
        nameFn(route);
      }
    }
  }
};
